/**
 * s_acpibatt.c
 * ACPI battery source for TrayInfo.
 * ACPI battery support added by Laszlo Ashin <kodest@gmail.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "trayinfo.h"
#include "utils.h"

static int
acpibatt_write(struct timeval *now, int fd)
{
	const char *idlist[] = {
		"remaining capacity",
		"charging state",
		"present rate"
	};
	char *vallist[] = { NULL, NULL, NULL };
	int rem, rate;

	collect_data_from_file(
		"/proc/acpi/battery/BAT0/state",
		":", 3, idlist, vallist
	);
	if (vallist[0]) {
		if (sscanf(vallist[0], "%d mWh", &rem) != 1)
			rem = 0;

		free(vallist[0]);
	}
	if (vallist[2]) {
		if (sscanf(vallist[2], "%d mW", &rate) != 1)
			rate = 0;

		free(vallist[2]);
	}
	if (vallist[1]) {
		if (!strcmp(vallist[1], "discharging") && rate > 0)
			rate = -rate;

		free(vallist[1]);
	}
	if (rate) {
		printf("%+dm", rem * 60 / rate);
		return 1;
	}
	return 0;
}

void
regsrc_acpibatt(src_t *src)
{
	src->name = "acpibatt";
	src->write = acpibatt_write;
}
